const bodyParser=require("body-parser")
const {getStoreDB}=require("./mongo")
const {getStoreDB}=require("./mongo")
const cookieParser=require("cookie-parser")
app.use(bodyParser.json());
app.use(cookieParser())
app.use("/products",productRouter)
app.get("/get_product",function(req,res){
    getStoreDB(function(storeDB){
        storeDB.collection("goods").find({}).toArray(function(err,result){
         if(err){
             res.send({
                status: 10002,
                msg: err.message
             })
             return
         }
            res.send({
                status: Const.SUCCESSFUL,
                msg: 'ok',
                data: {
                    result:result
                }
             }) 
       
        })
    })
})

app.post("/del_product",function(req,res){
    getStoreDB(function(storeDB){
        console.log(ObjectId(req.body._id))
        storeDB.collection("goods").remove({_id:ObjectId(req.body._id)},function(err,result){
         if(err){
             res.send({
                status: 10002,
                msg: err.message
             })
             return
         }
            res.send({
                status: Const.SUCCESSFUL,
                msg: 'ok',
                data: {
                    result:result
                }
             }) 
        })
    })
})

app.post("/add_product",function(req,res){
    getStoreDB(function(storeDB){
        storeDB.collection("goods").insert(req.body,function(err,result){
         if(err){
             res.send({
                status: 10002,
                msg: err.message
             })
             return
         }
            res.send({
                status: Const.SUCCESSFUL,
                msg: 'ok',
                data: {
                    result:result
                }
             }) 
        })
    })
})

app.post("/revise_product",function(req,res){
    getStoreDB(function(storeDB){
        var _id=req.body._id
        var {goods_name,price,number,dw}=req.body
        console.log(_id)
        storeDB.collection("goods").updateOne({_id:ObjectId(_id)},{$set:{goods_name,price,number,dw}},function(err,result){
         if(err){
             res.send({
                status: 10002,
                msg: err.message
             })
             return
         }
            res.send({
                status: Const.SUCCESSFUL,
                msg: 'ok',
                data: {
                    result:result
                }
             }) 
        })
    })
})